<?php

class Helper extends CController {

    public static function truncate_utf8_string($string, $length, $etc = '...') {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++) {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0')) {
                if ($length < 1.0) {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            } else {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen) {
            $result .= $etc;
        }
        return $result;
    }

    public static function datetime_to_date($date) {
        return date('Y-m-d', strtotime($date));
    }

    //获取汇率
    public static function getRate() {
        $row = Rate::model()->find();
        return $row->ExchangeRate;
    }

    //生成可用的productmodel
    public static function getProductModel() {
        $condition = new CDbCriteria();
        $condition->addCondition("ProductModel like 'B%'");
        $condition->addCondition('ProductID>1600');
        $condition->order = 'ProductModel DESC';
        $rowTable = Product::model()->findAll($condition);
        unset($condition);
        foreach ($rowTable as $row) {
            $num = substr($row->ProductModel, 1);
            if (strlen($num) == 5 && is_numeric($num)) {
                $num++;
                break;
            }
        }
        return 'B' . $num;
    }

    //生成可用的ordername
    public static function getOrderNumber() {
        return 'GAAA' . date('ym') . '01';
    }

    //生成可用的vendorcode
    public static function getVedorCode() {
        $condition = new CDbCriteria();
        $condition->addCondition("VendorCode like 'V%'");
        $condition->order = 'VendorCode DESC';
        $rowTable = Vendor::model()->findAll($condition);
        unset($condition);
        foreach ($rowTable as $row) {
            $num = substr($row->VendorCode, 1);
            if (strlen($num) == 3 && is_numeric($num)) {
                $num++;
                break;
            }
        }
        if (strlen($num) < 3) {
            for ($i = 0; $i < 3 - strlen($num); $i++) {
                $z .= '0';
            }
        }
        return 'V' . $z . $num;
    }

    //更新产品的AverageCost等
    public static function updateAvgCost($pid) {
        $product = Product::model()->findByPk($pid);
        if($product){
            $connection = Yii::app()->db;
            $sql = "SELECT sum(AmountUS)/sum(PQuantity) as AvgCost FROM [dbo].[Pricing] [t] WHERE BuySell='Buy' and ProductID=" . $product->ProductID;
            $command = $connection->createCommand($sql);
            $result = $command->queryAll();
            if ($result) {
                $product->AverageCost = $result[0]['AvgCost'];
                $product->LAAvgCost = $product->AverageCost * 1.2;
            }
            unset($result);
            
            $conditon = new CDbCriteria();
            $conditon->addCondition("ProductID=" . $product->ProductID);
            $conditon->addCondition("BuySell='Buy'");
            $conditon->order = 'PricingIndex DESC';
            $result = Pricing::model()->find($conditon);
            if ($result) {
                $product->FactoryCost = $result->PUintPrice;
                $product->LACost = $product->FactoryCost * 1.2;
            }
//            echo $result->PricingIndex.'<br />';
            unset($result);
            unset($conditon);
            
//            echo $product->ProductID.'<br />';
//            echo $product->ProductModel.'<br />';
//            echo $product->FactoryCost.'<br />';
//            echo $product->LACost.'<br />';
//            echo $product->AverageCost.'<br />';
//            
            $product->save();
//            var_dump($product->getErrors());exit;
        }
        
    }
    
    //规范链接
    public static function linkFormat($link){
        $pre = substr($link, 0,4);
        if($pre == 'http'){
            return $link;
        }else{
            return 'http://'.$link;
        }
    }
    
    //当pricing的验货反馈变化时，添加一条记录到iteam_feedback
    public static function addFeedback($content,$pricingid){
        $condition = new CDbCriteria();
        $condition->addCondition('status=1');
        $condition->addCondition('pricingid='.$pricingid);
        $model = IteamFeedback::model()->find($condition);
        unset($condition);
        if(!$model->fid){
            $model = new IteamFeedback;
        }        
        $model->content = $content;
        $model->pricingid = $pricingid;
        $model->status = 1;
        $model->save();
        
    }
    
    //添加产品是，生成NIDNo
    public static function getNIDNo(){
        $condition = new CDbCriteria();
        $condition->select = 'NIDNo';
        $condition->order='NIDNo desc';
        $condition->addCondition("NIDNo like 'S1%'");
        $model = Product::model()->find($condition);
        unset($condition);
        if($model){
            $NIDNo = substr($model->NIDNo, 1)+1;
        }else{
            $NIDNo = '100001';
        }        
        return 'S'.$NIDNo;
                
    }
    
    //生成GroupName
    public static function getGroupName(){
        $condition = new CDbCriteria();
        $condition->select = 'groupName';
        $condition->order='groupName desc';
        $condition->addCondition("groupName like '".  date('Ym')."%'");
        $model = IteamGroup::model()->find($condition);
        unset($condition);
        if($model){
            $groupName = $model->groupName+1;
        }else{
            $groupName = date('Ym').'00001';
        }        
        return $groupName;
    }
    
    //特殊词转换，导入amazon分类使用的
    public static function wordReplace($str,$type=1){
        $words = array(
            'I/O'=>'I|-|O',
            'PS/2'=>'PS|-|2',
        );
        foreach ($words as $key=>$word){
            if($type==1){
                $str1 = $key;
                $str2 = $word;
            }else{
                $str1 = $word;
                $str2 = $key;
            }
            $str = str_replace($str1, $str2, $str);
        }
        return $str;        
    }
    
    //MX的menu
    public static function mxMenu(){
        return in_array(substr(Yii::app()->user->name, 0,1), array('H','E'));
    }
    
    //多颜色产品统一入库
    public static function multiImport(){
        $connection = Yii::app()->db;
        $sql = "select count(*) as num,NIDNo from Product where NIDNo is not null and NIDNo!='' GROUP BY NIDNo ORDER BY num desc";
        $command = $connection->createCommand($sql);
        $result = $command->queryAll();
        if ($result) {
            foreach($result as $row){
                $model = Product::model()->find("NIDNo='".$row['NIDNo']."'");
                echo $row['num'].','.$row['NIDNo'].','.$model->ProductName.','.$model->ProductDetail.'
';
            }
        }
        unset($result);
    }
    
    //更新pricing运出缓存情况
    public static function updateTrackingCache($time=86400){
        $condition = new CDbCriteria();
        $condition->addCondition("UpdateTime>='".date('Y-m-d H:i:s', time()-$time)."'");
        $rowTable = Tracking::model()->findAll($condition);
        unset($condition);
        $trackingIds = CHtml::listData($rowTable, 'TrackingIndex', 'TrackingIndex');
        if($trackingIds){
            $trackingIdstring = implode(',', $trackingIds);
            $connection = Yii::app()->db;
            $sql = "select PricingIndex from MidTab where PricingIndex is not null and PricingIndex!='' and TrackingIndex in (" . $trackingIdstring . ") GROUP BY PricingIndex ORDER BY PricingIndex desc";
            $command = $connection->createCommand($sql);
            $result = $command->queryAll();
            if ($result) {
                foreach($result as $row){
                    Helper::updateTrackingCacheByPricingIndex($row['PricingIndex']);
                }
            }
        }
    }
    
    //根据PricingIndex更新运出缓存情况
    public static function updateTrackingCacheByPricingIndex($id){
        $model = Pricing::model()->findByPk((int)$id);
        if($model){
            $connection = Yii::app()->db;
            $sql = "select sum(ToLAQty) as num from MidTab m
    inner join Tracking t on t.TrackingIndex=m.TrackingIndex
    where m.PricingIndex='".$id."' and t.ShippingStatus='DataLogging'";
            $command = $connection->createCommand($sql);
            $row = $command->queryRow();
            
            $model->ToLAQty = (int)$row['num'];
            $model->save();
        }        
    }
    
    //获取某条pricing的可运出数量
    public static function getAbleNumByPricingIndex($id){
        Helper::updateTrackingCacheByPricingIndex($id);
        $model = Pricing::model()->findByPk((int)$id);
        if($model){
            return $model->Balance-$model->ToLAQty;
        }        
    }
    
    //获取某条mid记录的ToLAQty
    public static function getMidToLAQty($id){
        $model = MidTab::model()->findByPk((int)$id);
        return $model->ToLAQty;
    }
    
    //单引号转义
    public static function sqlFilter($str){
        return str_replace("'", "''", $str);
    }
    
    //添加NID时，生成NIDNum
    public static function getNIDNum(){
        $condition = new CDbCriteria();
        $condition->select = 'NIDNum';
        $condition->order='NIDNum desc';
        $model = NID::model()->find($condition);
        unset($condition);
        if($model){
            $NIDNum = substr($model->NIDNum, 1)+1;
        }else{
            $NIDNum = '10001';
        }        
        return 'N'.$NIDNum;
                
    }
}

?>